/*
@hehung
2023-2-8
转载请注明出处，版权由@hehung所有
email: 1398660197@qq.com
wechat: hehung95
*/

#include "hal_data.h"
#include "app_led.h"

#define LED_DEBUG
#undef LED_DEBUG

#ifdef LED_DEBUG
#include <stdio.h>
#endif

#define LED_ON                     (BSP_IO_LEVEL_HIGH)
#define LED_OFF                    (BSP_IO_LEVEL_LOW)



static uint8_t led_ctrl_flag = 1;
static uint32_t  led1_pwm = 0;



#if ((LED_CTRL_MODE == LED_DEMO_IO) || (LED_CTRL_MODE == LED_MODE_BOTH))
void Led_Ctrl(uint8_t led_num, uint8_t led_level)
{
    bsp_io_port_pin_t led_pin[LED_TOTAL_NUM] = 
    {
        BSP_IO_PORT_00_PIN_02
    };

    R_IOPORT_PinWrite(&g_ioport_ctrl, led_pin[led_num], led_level);
}
#endif 

#if ((LED_CTRL_MODE == LED_DEMO_PWM) || (LED_CTRL_MODE == LED_MODE_BOTH))
void Led_PwmCtrl(uint8_t led_num, uint32_t duty_cycle)
{
	fsp_err_t err = FSP_SUCCESS;
	
    if (LED_1 == led_num)
    {
        err = R_GPT_DutyCycleSet(&g_timer1_ctrl, duty_cycle, GPT_IO_PIN_GTIOCA);// duty cycle
        assert(FSP_SUCCESS == err);
    }
    else if (LED_2 == led_num)
    {
        err = R_GPT_DutyCycleSet(&g_timer3_ctrl, duty_cycle, GPT_IO_PIN_GTIOCB);// duty cycle
        assert(FSP_SUCCESS == err);
    }
	else
	{
#ifdef LED_DEBUG
		printf("Led: Error Led number parameter\n");
#endif 
	}
}
#endif 

void Led_Init(void)
{
    fsp_err_t err = FSP_SUCCESS;

	/* Initializes the module. */
	err = R_GPT_Open(&g_timer1_ctrl, &g_timer1_cfg);
	/* Handle any errors. This function should be defined by the user. */
	assert(FSP_SUCCESS == err);
	err = R_GPT_Open(&g_timer3_ctrl, &g_timer3_cfg);
	/* Handle any errors. This function should be defined by the user. */
	assert(FSP_SUCCESS == err);

	/* Start the timer1. */
	(void) R_GPT_Start(&g_timer1_ctrl);

    /* Start the timer3. */
	(void) R_GPT_Start(&g_timer3_ctrl);
	
	/* gpt timer1 for P405 */
    err = R_GPT_PeriodSet(&g_timer1_ctrl, 100);// frequency
    assert(FSP_SUCCESS == err);

	/* gpt timer1 for P404 */
    err = R_GPT_PeriodSet(&g_timer3_ctrl, 100);// frequency
    assert(FSP_SUCCESS == err);

    Led_PwmCtrl(LED_1, 0);
	Led_PwmCtrl(LED_2, 0);
}

void Led_LED_3_PwmSet(void)
{
    if (led_ctrl_flag == 0)
    {
        if (led1_pwm > 0)
			led1_pwm -= 1;
		else
			led1_pwm = 0;
    }
    else
    {
        if (led1_pwm < 100)
			led1_pwm += 1;
		else
			led1_pwm = 100;
    }
    Led_PwmCtrl(LED_1, (uint32_t)led1_pwm);
}

void Led_LED_2PwmSet(uint32_t pwm_set)
{
    if (pwm_set == 0)
    {
        Led_PwmCtrl(LED_2, 0);
    }
    else
    {
        Led_PwmCtrl(LED_2, 10000);
    }
}

void Led_ChangeStatus(uint8_t flag)
{
    led_ctrl_flag = flag;
}

// control the Lamp
void Led_LampPwmCtrl(uint8_t pwm_value)
{
    led1_pwm = pwm_value;
    Led_PwmCtrl(LED_1, (uint32_t)led1_pwm);
}

// get Lamp Pwm value
uint8_t Led_LampPwmGet(void)
{
    return (uint8_t)led1_pwm;
}

